package com.yonyou.cyxdms.sysAuth.service.service.dealerchannel;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoleilu.hutool.util.CollectionUtil;
import com.yonyou.cyx.framework.util.bean.ApplicationContextHelper;
import com.yonyou.cyx.function.exception.DALException;
import com.yonyou.cyx.function.utils.jsonserializer.JSONUtil;
import com.yonyou.cyxdms.framework.bean.dto.user_info.LoginInfoDto;
import com.yonyou.cyxdms.sysAuth.service.constants.ManageDictCodeConstants;
import com.yonyou.cyxdms.sysAuth.service.constants.SysAuthDictCodeConstants;
import com.yonyou.cyxdms.sysAuth.service.dto.dealer.MsgRecordDTO;
import com.yonyou.cyxdms.sysAuth.service.dto.dealer.MsgRecordManagePO;
import com.yonyou.cyxdms.sysAuth.service.dto.dealer.MsgRecordPO;
import com.yonyou.cyxdms.sysAuth.service.mapper.MsgRecordMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 服务实现类《通知》and《公告》
 * </p>
 *
 * @author duxiaoguang
 * @since 2019-09-04
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class MsgRecordServiceImpl extends ServiceImpl<MsgRecordMapper, MsgRecordPO> implements MsgRecordService {
    //日志对象
    private static final Logger logger = LoggerFactory.getLogger(MsgRecordServiceImpl.class);
    @Autowired
    MsgRecordMapper msgRecordMapper;

    @Autowired
    public MsgRecordService msgRecordService;

    /**
     * 通知
     * 分页查询对应数据
     *
     * @param page           分页对象
     * @param queryCondition 查询条件
     * @return com.baomidou.mybatisplus.core.metadata.IPage<java.util.Map < java.lang.String, java.lang.Object>>
     * @author duxiaoguang
     * @since 2018/7/22 0022
     */
    @Override
    @SuppressWarnings("unchecked")
    @Transactional(readOnly = true)
    public IPage<Map<String, Object>> selectPageBysql(Page page, Map<String, Object> queryCondition) {
        // 获取总条数
        page.setRecords(msgRecordMapper.selectPageAll(page, queryCondition));
        return page;
    }

    @Override
    @SuppressWarnings("unchecked")
    public IPage<Map<String, Object>> selectPageByTzs(Page page, Map<String, Object> queryCondition) {
        // 获取总条数
        page.setRecords(msgRecordMapper.selectPageByTz(page, queryCondition));
        List<MsgRecordDTO> msgList = msgRecordMapper.selectPageByTz(page, queryCondition);
        for (MsgRecordDTO dto : msgList) {
            if (70281040 == dto.getTemplateCode()) {
                MsgRecordPO po = msgRecordMapper.selectById(dto.getMsgId());
                po.setMsgStatus(ManageDictCodeConstants.RELEASE_STATUS_YES);
                msgRecordMapper.updateById(po);
            }
        }
        return page;
    }

    @Override
    public List<Map<String, String>> selectMsgType() {
        return msgRecordMapper.selectMsgType();
    }

    /**
     * 根据ID 进行删除数据
     *
     * @return void
     * @since 2018/8/25 0025
     */
    @Override
    public Integer deleteById(Integer userId) {
        Integer isDelate = msgRecordMapper.deleteAll(userId);
//        Integer par = msgRecordMapper.selectByIds(userId);
//        if(par<=0){
//            throw new DALException("列表已经清空！");
//        }
        logger.debug("删除：{}", isDelate);
        if (isDelate <= 0) {
            throw new DALException("列表已经清空！");
        }
        return isDelate;
    }

    /**
     * 公告
     *
     * @param page
     * @param queryCondition
     * @return
     */
    @Override
    public IPage<Map<String, Object>> selectPageNotice(Page page, Map<String, Object> queryCondition) {
        page.setRecords(msgRecordMapper.selectPageByGg(page, queryCondition));
        return page;
    }

    @Override
    public Integer addNotice(MsgRecordDTO msgRecordDTO) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        //对对象进行赋值操作
        MsgRecordPO msgrecordpo = msgRecordDTO.transDtoToPo(MsgRecordPO.class);
        msgrecordpo.setMsgCode("GG");
        msgrecordpo.setAppId(loginInfoDto.getAppId());
        msgrecordpo.setMsgTitle(msgRecordDTO.getMsgTitle());
        msgrecordpo.setMsgContent(msgRecordDTO.getMsgContent());
        //查找发布人角色的数据来源
        Integer noticeSource = msgRecordMapper.queryDataSource(Math.toIntExact(loginInfoDto.getUserId()));
        msgrecordpo.setMsgNoticeSource(noticeSource);
        //新增数据默认未发布
        // msgRecordPO.setMsgStatus(SysAuthDictCodeConstants.MSG_STATUS_NO);
        msgrecordpo.setNoticeConfirm(msgrecordpo.getNoticeConfirm());
        msgrecordpo.setIsDeleted(SysAuthDictCodeConstants.STATUS_IS_NOT);
        if (msgRecordDTO.getMsgStatus() == SysAuthDictCodeConstants.MSG_STATUS_NO) {
            msgrecordpo.setMsgStatus(SysAuthDictCodeConstants.MSG_STATUS_NO);//已发布
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            String format = df.format(new Date());
            msgrecordpo.setMsgNoticeTime(format);
        } else if (msgRecordDTO.getMsgStatus() == SysAuthDictCodeConstants.MSG_STATUS_IS) {
            msgrecordpo.setMsgStatus(SysAuthDictCodeConstants.MSG_STATUS_IS);//默认待发布()
        }
        return msgRecordMapper.addNotice(msgrecordpo);
    }

    @Override
    public List<Map<String, String>> queryNotices(Integer msgId) {
        MsgRecordDTO msgRecordDTO = new MsgRecordDTO();
        msgRecordDTO.setNoticeRead(SysAuthDictCodeConstants.NOTICE_FONFIRM_READ_IS);
        //查询公告是否需要确认
        List<Map<String, String>> maps = msgRecordMapper.queryMsgConfirmIs(msgId);
        if (maps.size() > 0) { //进入待确认
            msgRecordDTO.setNoticeConfirm1(SysAuthDictCodeConstants.NOTICE_FONFIRM_NO);
        }
        updateStatus(msgId, msgRecordDTO);
        return msgRecordMapper.queryNotices(msgId);
    }

    @Override
    public List<Map<String, String>> queryNoticesMobile(Integer userId) {
        return msgRecordMapper.queryNoticesMobile(userId);
    }

    /**
     * 清空公告
     *
     * @param userId
     * @return
     */
    @Override
    public Integer deleteByIdGg(Integer userId) {
        Integer isDelate = msgRecordMapper.deleteByIdGg(userId);
        logger.debug("删除：{}", isDelate);
        if (isDelate <= 0) {
            throw new DALException("列表已经清空！");
        }
        return isDelate;
    }


    /**
     * 公告维护详情-已确认/待确认
     */
    @Override
    public List<Map<String, String>> queryNoticeMaintain(Integer msgId) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
//        List<Map<String, String>> maps = msgRecordMapper.queryNoticeMaintain(msgId, Math.toIntExact(loginInfoDto.getUserId()));
//        Integer noticeConfirm = null;
//        for (Map<String, String> m : maps) {
//            for (Map.Entry value : m.entrySet()) {
//                noticeConfirm = (Integer) value.getValue();
//            }
//        }
        return msgRecordMapper.queryNoticeMaintain(msgId, Math.toIntExact(loginInfoDto.getUserId()));
    }


    /**
     * 确认及修改阅读状态（已确认或取消/已读）
     *
     * @param msgRecordDTO
     */
    @Override
    public List<MsgRecordDTO> updateStatus(Integer msgId, MsgRecordDTO msgRecordDTO) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        if (msgRecordDTO.getMsgStatus() == SysAuthDictCodeConstants.MSG_STATUS_NO) {
            MsgRecordPO msgrecordpo = new MsgRecordPO();
            msgrecordpo.setMsgId(msgRecordDTO.getMsgId());
            msgrecordpo.setMsgStatus(SysAuthDictCodeConstants.MSG_STATUS_IS);//已发布//msgRecordPO.setMsgNoticeTime(System.currentTimeMillis());
            msgRecordMapper.updateNoticeMsgStatus(msgrecordpo);
        } else {
            //查询表中是否存再msgId和userId，如果不存在，则插入新数据
            List<Map<String, String>> maps = msgRecordService.queryNoticeMange(msgId);
            MsgRecordManagePO msgRecordManage = null;
            if (maps.size() < 1) {
                msgRecordManage = new MsgRecordManagePO();
                msgRecordManage.setMsgId(msgId);
                msgRecordManage.setUserId(Math.toIntExact(loginInfoDto.getUserId()));
                msgRecordManage.setNoticeRead(SysAuthDictCodeConstants.NOTICE_FONFIRM_READ_IS);  //公告阅读状态
                msgRecordManage.setNoticeConfirm(msgRecordDTO.getNoticeConfirm1());//公告确认状态
                msgRecordManage.setIsDeleted(10041002);
                msgRecordMapper.addNoticeMange(msgRecordManage);
            } else {
                msgRecordManage = new MsgRecordManagePO();
                msgRecordManage.setMsgId(msgId);
                msgRecordManage.setUserId(Math.toIntExact(loginInfoDto.getUserId()));
                Integer noticeRead = msgRecordDTO.getNoticeRead();
                if (noticeRead == 10041002) {
                    msgRecordManage.setNoticeRead(SysAuthDictCodeConstants.NOTICE_FONFIRM_READ_IS);  //公告阅读状态
                }
                Integer noticeConfirm = msgRecordDTO.getNoticeConfirm1();
                if (noticeConfirm == SysAuthDictCodeConstants.NOTICE_FONFIRM_NO) {
                    msgRecordManage.setNoticeConfirm(SysAuthDictCodeConstants.NOTICE_FONFIRM_IS);//公告确认状态
                }
                msgRecordMapper.updateStatus(msgRecordManage);
            }
        }
        Page<MsgRecordDTO> page = new Page(1, 10);
        Map<String, Object> queryCondition = new HashMap<>();
        queryCondition.put("userId", loginInfoDto.getUserId());
        return msgRecordMapper.selectPageByGg(page, queryCondition);
    }
    /**
     * 打印申请单号变更通知状态
     *
     * @param msgRecordDTO
     */
    @Override
    public void printUpdateStatus(List<MsgRecordDTO> msgRecordDTO) {
        logger.info("msgRecordDTO============>{}", JSONUtil.objectToJson(msgRecordDTO));
        if(!CollectionUtil.isEmpty(msgRecordDTO)){
            for (MsgRecordDTO recordDTO : msgRecordDTO) {
                msgRecordMapper.printUpdateStatus(recordDTO);
            }
        }
    }


    /**
     * 公告维护
     *
     * @param msgRecordDTO
     */
    @Override
    public void updateNotice(MsgRecordDTO msgRecordDTO) {
        MsgRecordPO msgrecordpo = new MsgRecordPO();
        msgrecordpo.setMsgId(msgRecordDTO.getMsgId());
        msgrecordpo.setMsgTitle(msgRecordDTO.getMsgTitle());
        msgrecordpo.setMsgContent(msgRecordDTO.getMsgContent());
        msgrecordpo.setNoticeConfirm(msgRecordDTO.getNoticeConfirm());
        msgRecordMapper.updateNotice(msgrecordpo);
    }


    @Override
    public List<Map<String, String>> queryNoticeMange(Integer msgId) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        return msgRecordMapper.queryNoticeMange(msgId, Math.toIntExact(loginInfoDto.getUserId()));
    }


    //已确认人
    @Override
    public List<Map<String, String>> queryNoticeIs(Integer msgId) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        return msgRecordMapper.queryNoticeIs(msgId);
    }

    //待确认
    @Override
    public List<Map<String, String>> queryNoticeNo(Integer msgId) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        return msgRecordMapper.queryNoticeNo(msgId);
    }

    /**
     * 公告维护查看
     *
     * @param page
     * @param queryCondition
     * @return
     */
    @Override
    public IPage<Map<String, Object>> queryNotice(Page page, Map<String, Object> queryCondition) {
        page.setRecords(msgRecordMapper.queryNotiry(page, queryCondition));
        return page;
    }


    /**
     * 点击收到更新状态
     *
     * @param msgRecordDTO
     */
    @Override
    public void updateStatusIo(Integer msgId) {
        LoginInfoDto loginInfoDto = ApplicationContextHelper.getBeanByType(LoginInfoDto.class);
        //查询表中是否存再msgId和userId，如果不存在，则插入新数据
        List<Map<String, String>> maps = msgRecordService.queryNoticeMange(msgId);
        MsgRecordManagePO msgRecordManage = null;
        if (maps.size() < 1) {
            msgRecordManage = new MsgRecordManagePO();
            msgRecordManage.setMsgId(msgId);
            msgRecordManage.setUserId(Math.toIntExact(loginInfoDto.getUserId()));
            msgRecordManage.setNoticeRead(SysAuthDictCodeConstants.NOTICE_FONFIRM_READ_IS);  //公告阅读状态
            msgRecordManage.setNoticeConfirm(SysAuthDictCodeConstants.NOTICE_FONFIRM_IS);//公告确认状态
            msgRecordManage.setIsDeleted(10041002);
            msgRecordMapper.addNoticeMange(msgRecordManage);
        } else {
            msgRecordManage = new MsgRecordManagePO();
            msgRecordManage.setMsgId(msgId);
            msgRecordManage.setUserId(Math.toIntExact(loginInfoDto.getUserId()));
            msgRecordManage.setNoticeRead(SysAuthDictCodeConstants.NOTICE_FONFIRM_READ_IS);  //公告阅读状态
            msgRecordManage.setNoticeConfirm(SysAuthDictCodeConstants.NOTICE_FONFIRM_IS);//公告确认状态
            msgRecordMapper.updateStatus(msgRecordManage);
        }
        Page<MsgRecordDTO> page = new Page(1, 10);
        Map<String, Object> queryCondition = new HashMap<>();
        queryCondition.put("userId", loginInfoDto.getUserId());
        msgRecordMapper.selectPageByGg(page, queryCondition);
    }

    @Override
    public Integer addnoticecc(MsgRecordDTO msgRecordDTO) {
        //对对象进行赋值操作
        MsgRecordPO msgRecordPO = msgRecordDTO.transDtoToPo(MsgRecordPO.class);
        msgRecordPO.setMsgType(msgRecordDTO.getMsgType());
        msgRecordPO.setTemplateCode(70281022);
        //新增数据默认未发布
        // msgRecordPO.setMsgStatus(SysAuthDictCodeConstants.MSG_STATUS_NO);
        msgRecordPO.setIsDeleted(SysAuthDictCodeConstants.STATUS_IS_NOT);
        if (msgRecordDTO.getMsgStatus() == SysAuthDictCodeConstants.MSG_STATUS_NO) {
            msgRecordPO.setMsgStatus(SysAuthDictCodeConstants.MSG_STATUS_NO);//已发布
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            String format = df.format(new Date());
            msgRecordPO.setMsgNoticeTime(format);
        } else if (msgRecordDTO.getMsgStatus() == SysAuthDictCodeConstants.MSG_STATUS_IS) {
            msgRecordPO.setMsgStatus(SysAuthDictCodeConstants.MSG_STATUS_IS);//默认待发布()
        }
        msgRecordMapper.addNoticeCC(msgRecordPO);
        return msgRecordPO.getMsgId();
    }
}
